package cn.autumnorange.authorization.security.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

@Configuration
public class FeignHeaderInterceptor implements RequestInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(FeignHeaderInterceptor.class);

    @Override
    public void apply(RequestTemplate requestTemplate) {

        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                requestTemplate.header(name, values);
            }
        }
        //    没有覆盖原方法多次写入参数值。。。
        //    Enumeration<String> bodyNames = request.getParameterNames();
        //    StringBuffer body = new StringBuffer();
        //    if (bodyNames != null) {
        //      while (bodyNames.hasMoreElements()) {
        //        String name = bodyNames.nextElement();
        //        String values = request.getParameter(name);
        //        body.append(name).append("=").append(values).append("&");
        //      }
        //    }
        //    if (body.length() != 0) {
        //      body.deleteCharAt(body.length() - 1);
        //      requestTemplate.body(body.toString());
        //      LOGGER.info("feign interceptor body:{}", body.toString());
        //    }
    }
}
